<?php


namespace app\common\controller\platform;


use app\admin\service\RbacService;
use app\common\enum\MainEnum;
use app\common\exception\ForbiddenException;
use app\common\exception\ParameterFailedException;
use app\common\model\UserModel;

class Admin implements PlatformInterface
{
    public static function register()
    {
        // TODO: Implement register() method.
    }

    public static function login($data)
    {
        // 验证账号密码
        $userModel = UserModel::where('mobile_number', $data['mobile_number'])
            ->field('id,password,salt,group_id')
            ->find();
        if (!$userModel) {
            throw new ForbiddenException(
                [
                    'msg'  => '用户不存在',
                    'code' => MainEnum::ERROR_TOKEN_ERROR,
                ]
            );
        }
        if (!decryptPassword($data['password'], $userModel->password, $userModel->salt)) {
            throw new ParameterFailedException(['msg' => '用户名与密码不匹配']);
        }
        if ($userModel->getData('group_id') !== MainEnum::GROUP_ADMIN) {
            throw new ForbiddenException(
                [
                    'msg'  => '用户非管理员',
                    'code' => MainEnum::ERROR_TOKEN_ERROR,
                ]
            );
        }

        $userModel->save();
        $platform_specific = basename(str_replace('\\', '/', get_class(new self())));
        $accessToken       = RbacService::setToken($userModel->getData('id'), $platform_specific);
        return ['access_token' => $accessToken];
    }

    public static function loginOut($request)
    {
        $request->userPlatformTokenModel->force()->delete();
    }

    public static function removeToken()
    {
        // TODO: Implement removeToken() method.
    }
}